// xc/components/widgets/reg.js

Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    themcolor: { // 属性名
      type: Object,
      value: null
    },
    zindex:{
      type: Number,
      value: 1000
    }
  },

  ready() {
    if(wx.getUserProfile){     
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    if(!this.data.themcolor){
      
      const app= getApp();
      if(app.globalData.configdata && app.globalData.configdata.prothem){
        var themcolor=app.globalData.configdata.prothem.themcolor.config;
      }else{
        var themcolor={
          primarycolor:"#69BC6F",
          secondraycolor:"#B3DFB7",
          pritextcolor:"#333333",
          sectextcolor:"#999999",
        }
      }
      this.setData({
        themcolor
      })
    }

  },
  /**
   * 组件的初始数据
   */
  data: {
    canIUseGetUserProfile:false,  //2021-4 登录
    active: 0,
    isshow: false,
    moreinfoshow: false,
    title: "",
    remark: "",
    logourl: "",
    auth: {},
    steps: null,
    name:"",
     invitecode:"",
     sex:"",
     backfun:null,
     usermodel: { phone: "" }
    // steps: [
    //   {
    //     text: '授权手机号',
    //     desc: '获取你的手机号用于实名认证',
    //     inactiveIcon: 'checked',
    //     activeIcon: 'checked',
    //   }          
    // ],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    avatarchange(e){
      console.log(e)
      this.setData({
        'headimgurl':e.detail.fullpath
      })

    },
    //获取邀请者分销商信息
    distriuser(uid){
      var that = this;
      var app = getApp();
      console.log("gggggg")

      app.util.request({
        'url': 'entry/wxapp/distribution_manage',
        showLoading: false,
        method: 'POST',
        data: {
          op: 'user',
          uid: uid
        },
        success(res) {
          var data=res.data.data;

          if(data['status']==1){
            that.setData({
              invitecode:data['obj']['invitcode'],
               distriuser: data['obj']
            })
          }
          

        },
        fail(res) {

        }
      })
    },
    isreg(){
      if (this.data.active == this.data.steps.length - 1) {
       return 1
      }
       return -1
    },
    nextstep(){
      var updatemodel={}
      updatemodel["active"] = this.data.active + 1
      if (this.data.active + 1 == 2) {
          var app = getApp()
          if (app.globalData.member && app.globalData.member.from_share_id && app.globalData.member.from_share_id!=0) {
            this.distriuser(app.globalData.member.from_share_id)
          }
        }
      this.setData(updatemodel)
    },
    //获取手机号码
    getPhoneNumber(e) {
      console.log(e,'====')
      var app = getApp()
      var that = this;
      var dataset = e.currentTarget.dataset;
      var isreg = this.isreg();    
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      var code=e.detail.code
      var that = this;
      app.util.request({
        'url': 'entry/wxapp/sys_reg',
        showLoading: false,
        method: 'POST',
        data: {
          op: 'getphone',
          encryptedData: encryptedData,
          iv: iv,
          isreg: isreg,
          code:code
        },
        success(res) {
          var parm = res.data.data;
          if (parm["status"] == 1) {
            var updatemodel = {};
            updatemodel["usermodel.phone"] = parm["obj"].phoneNumber;
            if (dataset.op != "modfily") {
              if (isreg == 1) {
                app.globalData.member = parm.obj;
                that.successreg(parm.obj);
              }
              else
              {
                that.nextstep()
              }
            }
            that.setData(updatemodel)
          }
          else {
            wx.showModal({
              title: '提示',
              content: parm["message"],
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        }
      })
    },
    GetUserProfile(e){
      var that = this;
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          var app =getApp()
          var encryptedData = res.encryptedData;
          var iv = res.iv;
          var that = this;
          var isreg = this.isreg();
          if (that.data.active == that.data.steps.length - 1) {
            isreg = 1;
          }
          app.util.request({
            'url': 'entry/wxapp/sys_reg',
            showLoading: false,
            method: 'POST',
            data: {
              op: 'weixiinfo',
              encryptedData: encryptedData,
              iv: iv,
              isreg: isreg
            },
            success(res) {
              var parm = res.data.data;
              if (parm["status"] == "41009") {
                wx.setStorageSync('userInfo', '');
                that.GetUserProfile(null);
                return;
              }
              if (parm.status == 1) {
                if (isreg == 1) {
                  app.globalData.member = parm.obj;
                  that.successreg(parm.obj);
                }
                else
                {
                  if(parm.obj&&parm.obj.gender){
                    that.setData({sex:parm.obj.gender.toString()})
                  }
                  that.nextstep()
                }
               
              //  that.setData({ step: that.data.step + 1 })
              }else{
                wx.showModal({
                  title:"错误",
                  content:parm['message'],
                })
              }
            },
            fail(res) {
            }
          })
        }
      })
    },
    handleAgreePrivacyAuthorization() {
      var that=this;
      if(wx.onNeedPrivacyAuthorization){
        wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
          console.log('触发本次事件的接口是：' + eventInfo.referrer)
          // 需要用户同意隐私授权时
          // 弹出开发者自定义的隐私授权弹窗
          that.selectComponent("#privacypopup").show()
         
          this.resolvePrivacyAuthorization = resolve
        })
      }

      // 用户同意隐私协议事件回调
      // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
      // wx.getUserProfile()
      // wx.chooseMedia()
      // wx.getClipboardData()
      // wx.startRecord()
    },
    handleTouchInput(){
      var that=this;
      if(wx.requirePrivacyAuthorize){
        wx.requirePrivacyAuthorize({
          success: res => {
            console.log('用户同意了隐私协议 或 无需用户同意隐私协议')
            // 用户同意隐私协议后给昵称input聚焦
            this.setData({
              focus: true
            })
          },
          fail: res => {
            console.log('用户拒绝了隐私协议')
          }
        })
      }else{
        this.setData({
          focus:true
        })
      }
    },
    agree() {
      // 用户点击同意按钮后
      this.resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
      // 用户点击同意后，开发者调用 resolve({ buttonId: 'agree-btn', event: 'agree' })  告知平台用户已经同意，参数传同意按钮的id
      // 用户点击拒绝后，开发者调用 resolve({ event:'disagree' }) 告知平台用户已经拒绝
    },
    disagree(){
    
      this.resolvePrivacyAuthorization({event:'disagree' })

       wx.showToast({
         type:"error",
         title: '已拒绝',
       })
    },
    //获取用户信息
    getuserinfo(e) {
      console.log("getuserinfo")
      var app =getApp()
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      var that = this;
      var isreg = this.isreg();
      if (that.data.active == that.data.steps.length - 1) {
        isreg = 1;
      }
      app.util.request({
        'url': 'entry/wxapp/sys_reg',
        showLoading: false,
        method: 'POST',
        data: {
          op: 'weixiinfo',
          encryptedData: encryptedData,
          iv: iv,
          isreg: isreg
        },
        success(res) {
          var parm = res.data.data;
          if (parm["status"] == "41009") {
            wx.setStorageSync('userInfo', '');
            app.util.getUserInfo(function (params) {
              wx.showToast({
                title: '请重新授权',
              })
            })
            return;
          }
          if (parm.status == 1) {
            if (isreg == 1) {
              app.globalData.member = parm.obj;
              that.successreg(parm.obj);
            }
            else
            {
              that.nextstep()
            }
           
          //  that.setData({ step: that.data.step + 1 })
          }
        },
        fail(res) {
        }
      })
    },

    successreg(info) {      
      var that = this;
      wx.showToast({
        title: '注册成功',
      })
      that.setData({ "isshow": false })
      var myEventOption = {} // 触发事件的选项
      if (info) {
        myEventOption = info;
      }
      that.triggerEvent('successreg', {}, myEventOption)
      if(this.data.backfun){
        this.data.backfun(myEventOption)
      }
    },
    show(backfun) {
      var that=this;
     
      if(backfun){
        this.data.backfun=backfun;
      }
      var app = getApp();
      // app.vent.Notify('通知内容')
      // console.log("通知内容")
      if (app.globalData) {
        var authorization = app.globalData.configdata.authorization    
        var newsteps = []
        var fileds = ["phone", "moreinfo"]
        fileds.forEach(item => {
          if (authorization[item].status == "1") {
            newsteps.push({
              text: authorization[item].title,
              desc: authorization[item].tips,
              inactiveIcon: 'checked',
              activeIcon: 'checked',
              field: item
            })
          }
        })
        if (newsteps.length > 0) {
          this._showmodel(newsteps, authorization)
        }
        else {
          this.regmember();
        }
      }
    },
    _showmodel(newsteps, authorization) {
      var updatemodel = {}
      if (newsteps.length == 1 && newsteps[0].field == "moreinfo") {
        updatemodel["moreinfoshow"] = true
      }
      updatemodel["steps"] = newsteps
      updatemodel["isshow"] = true
      updatemodel["auth"] = authorization  
      this.setData(updatemodel)
    },
    closereg(){
           this.setData({isshow:false})
    },
    onsexChange(ev){
      this.setData({"sex":ev.detail})  

    },
    fromsubit() {      
      var app =getApp();
      var tipdata = [];
     var moreinfo =this.data.auth["moreinfo"]
      for(var field in moreinfo.fields) {
        if(moreinfo.fields[field].status=="1" && moreinfo.fields[field].ismust!="-1"){
          console.log("ssssssssssssssssssssss")
          console.log(field)
          console.log(this.data[field])
          // if(field=='headimgurl'){
          //   avatarUrl
          // }

          if((!this.data[field])){
              tipdata.push(moreinfo["fields"][field].tips+"不能为空");         
          }
        } 
      } 

      
      if (tipdata.length > 0) {
        wx.showModal({
          title: '错误',
          content: tipdata.join("\r\n"),
        })
        return;
      }
      var model = {};     
      model.name = this.data.name;
      model.sex = this.data.sex;
      model.invitecode = this.data.invitecode;
      model.nickname = this.data.nickname;
      model.headimgurl = this.data.headimgurl;

      var that= this;
      app.util.request({
        'url': 'entry/wxapp/sys_reg',
        showLoading: false,
        method: 'POST',
        data: {
          op: 'reguser',
          regdata: JSON.stringify(model)
        },
        success(res) {
          app.globalData.member = res.data.data.obj;
          that.successreg(res.data.data.obj);
          that.setData({isshow:false})

         
        },
        fail(res) {
          wx.showModal({
            title: '错误',
            content: res["data"]["message"],
            showCancel: false,
            success(res) {
              if (res.confirm) {

              } else if (res.cancel) {

              }
            }
          })
          
        }
      })
    },
    regmember() {
    },
  }
})
